package com.seata.cloud.service.impl;

import com.seata.cloud.AccountFacede;
import com.seata.cloud.StorageFacede;
import com.seata.cloud.dao.OrderDAO;
import com.seata.cloud.entity.Order;
import com.seata.cloud.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单业务实现类
 * Created by macro on 2019/11/11.
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderDAO orderDao;
    
    @Autowired
    private StorageFacede storageFacede;
    
    @Autowired
    private AccountFacede accountFacede;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     */
    @Override
    @GlobalTransactional
    public void create(Order order) {
        log.info("------->下单开始");
        //本应用创建订单
        orderDao.create(order);
        //测试异常回滚
        Integer num = 10/0;

        //远程调用账户服务扣减余额
        log.info("------->order-service中扣减余额开始");
        accountFacede.decrease(order.getUserId(),order.getMoney());
        log.info("------->order-service中扣减余额结束");
        
        //远程调用库存服务扣减库存
        log.info("------->order-service中扣减库存开始");
        storageFacede.decrease(order.getProductId(),order.getCount());
        log.info("------->order-service中扣减库存结束");

        //修改订单状态为已完成
        log.info("------->order-service中修改订单状态开始");
        orderDao.update(order.getUserId(),1);
        log.info("------->order-service中修改订单状态结束");

        log.info("------->下单结束");
    }
    
}
